﻿using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework;
using ConfigManager.TabPages;
using ComLib.ConfigService;
using LogLib;
using ComUIControl;
using System.IO;
using System.Threading.Tasks;
using ProcessConfig;
using ConfigManager.ChildForms;

namespace ConfigManager
{
    public partial class FormConfigManager : MetroForm
    {
        private string _errorMsg = "";

        /// <summary>
        /// PXL类库是否需要初始化
        /// </summary>
        private bool _bPxlNeedInit = false;

        /// <summary>
        /// 配置数据
        /// </summary>
        private ConfigService _config;
        public ConfigService Config
        {
            get { return _config; }
        }

        /// <summary>
        /// 配置页面列表
        /// </summary>
        private List<TabPageBase> listTabPages = new List<TabPageBase>();

        private TabPageDetectPhoto tabPageDetectPhoto;
        private TabPageApplyOption tabPageAppOption;

        public FormConfigManager(ConfigService config, bool pxlNeedInit)
        {
            _config = config;
            _bPxlNeedInit = pxlNeedInit;
            InitializeComponent();
            ResetTabPageSeqence();
        }

        private void ResetTabPageSeqence()
        {
            this.metroTabControl1.Controls.Clear();
            this.metroTabControl1.Controls.Add(this.metroTabPageDetectPhoto);
            this.metroTabControl1.Controls.Add(this.metroTabPageAdjustImage);
            this.metroTabControl1.Controls.Add(this.metroTabPageApplyType);
        }

        public void InitTabPages()
        {
            tabPageAppOption = new TabPageApplyOption();
            tabPageDetectPhoto = new TabPageDetectPhoto();
        
            listTabPages.Add(tabPageDetectPhoto);
            listTabPages.Add(tabPageAppOption);

            metroTabPageDetectPhoto.Controls.Add(tabPageDetectPhoto);
            metroTabPageApplyType.Controls.Add(tabPageAppOption);         
        }

        public void InitCtrls()
        {
            try
            {
                TabPageBase.InitCompleted = false;
                for (int i = 0; i < listTabPages.Count; i++)
                {
                    try
                    {
                        listTabPages[i].InitCtrls();
                    }
                    catch (Exception ex)
                    {
                        _errorMsg = ex.ToString();
                        Log.WriteException(ex.ToString());
                    }
                }
                TabPageBase.InitCompleted = true;
            }
            catch (Exception ex)
            {
                _errorMsg = ex.ToString();
                Log.WriteException(ex.ToString());
            }
        }

        public void ExitPages()
        {
            try
            {
                for (int i = 0; i < listTabPages.Count; i++)
                {
                    listTabPages[i].Exit();
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }
        }

        public bool UpdateData()
        {
            for (int i = 0; i < listTabPages.Count; i++)
            {
                if (!listTabPages[i].UpdateData())
                {
                    return false;
                }
            }
            return true;
        }

        private void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            Log.Exit();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            if (_bPxlNeedInit && !Log.Inialized)
            {
                this.Close();
                return;
            }
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            InitTabPages();
            InitCtrls();
            if (!TabPageBase.InitCompleted)
            {
                ComBox.ShowErrorMessage(this, "程序启动发生了异常: " + _errorMsg, "程序启动异常");
            }
           
            Log.AddBeginningBoundary();
            Log.WriteAsync("Enter 系统配置");
            Log.WriteAsync("更改之前的系统配置");
            WriteAllConfigValues();
            WaitingBox.Close();
        }

        public void WriteAllConfigValues()
        {
            Log.AddBoundary("配置内容开始");
            List<string> arrays = Config.GetAllConfigValues();
            Log.WriteAsync(arrays);
            Log.AddBoundary("配置内容结束");
        }
    
        private void Form_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            ExitPages();          
            Log.WriteAsync("Exit 系统配置");
            Log.AddEndingBoundary();
            Log.Exit();
        }

        private void buttonCancell_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (!UpdateData())
            {
                return;
            }

            Log.WriteAsync("修改后的所有配置信息如下:");
            WriteAllConfigValues();
            // 当在主程序界面
            if (!_bPxlNeedInit)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
                return;
            }
            if (ConfigManage.SaveSettings())
            {
                ConfigService service = ConfigManage.Service;
                if (!service.CheckSaveAllSuccess())
                {
                    string[] errArray = service.GetSaveErrors();
                    string title = "部分参数保存异常，异常详细信息如下:";
                    FormErrorMessage form = new FormErrorMessage(title, errArray);
                    form.ShowDialog();
                }
                else
                {
                    AutoMetroMessageBox.Show(this, "配置更改成功.", "配置修改提示", MessageBoxButtons.OK, MessageBoxIcon.Information, 250, 5);
                }
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            else
            {
                AutoMetroMessageBox.Show(this, "配置保存失败.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error, 250, 5);
            }        
        }
    }
}
